package edu.ucla.cs.typecast.ping;

import java.io.*;
import java.net.*;
import java.util.*;

import edu.ucla.cs.typecast.net.NetUtil;
import edu.ucla.cs.typecast.net.TypeCastConstants;
import edu.ucla.cs.typecast.util.slf.ScriptLogReader;

public class PingReceiverApp {
	/**
	 * Main function.
	 * 
	 * @param args
	 * @throws IOException
	 */

	public static void main(String[] args) throws IOException {
		// Read config file if it exists

		final File configFile = new File("pingsender.conf");

		Map<String, String> config = new HashMap<String, String>();
		if (configFile.exists() && configFile.canRead()) {
			ScriptLogReader slr = new ScriptLogReader(configFile, true);
			config = slr.readEntry();
		}

		// Read parameters

		final InetAddress privateHost = InetAddress.getByName(ScriptLogUtil
				.readString(config, "private_host", NetUtil.getLocalHost()
						.getHostAddress()));

		final int privatePort = ScriptLogUtil.readInt(config, "private_port",
				PingUtil.randPort());

		final InetAddress publicHost = InetAddress.getByName(ScriptLogUtil
				.readString(config, "public_host",
						TypeCastConstants.DEFAULT_RMI_ADDRESS));

		final int publicPort = ScriptLogUtil.readInt(config, "public_port",
				TypeCastConstants.DEFAULT_RMI_PORT);

		// Create a ping receiver that prints a message when it receives a ping

		new PingReceiverImplForConsole(privateHost, privatePort, publicHost,
				publicPort);

		// Print the arguments
		// The RMI thread will not quit, so we can quit this thread after

		System.out.println("Private: " + privateHost + ":" + privatePort);
		System.out.println("Public: " + publicHost + ":" + publicPort);
		System.out.println("Listening...");
	}
}

/**
 * An implementation of PingSender tailored for the "ping program".
 */

class PingReceiverImplForConsole extends PingReceiverImpl implements
		PingReceiver {
	protected static final long serialVersionUID = 1L;

	public PingReceiverImplForConsole(InetAddress privateHost, int privatePort,
			InetAddress publicHost, int publicPort) throws IOException {
		super(privateHost, privatePort, publicHost, publicPort);
	}

	public PingReceiverImplForConsole(String privateHost, int privatePort,
			String publicHost, int publicPort) throws IOException {
		super(privateHost, privatePort, publicHost, publicPort);
	}

	public void receivePing(InetAddress senderHost, int senderPort, int seqNum)
			throws IOException {
		super.receivePing(senderHost, senderPort, seqNum);

		System.out.println("Received ping from (and sent a pong to) "
				+ senderHost + ":" + senderPort + ", seq # " + seqNum);
	}
}
